﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TXTD.Admin.Data.Entitys.System;
using TXTD.Admin.Interface.System;

namespace TXTD.Admin.ScheduledTask.Listeners
{
    /// <summary>
    /// job监听
    /// </summary>
    public class JobServiceListener : IJobListener
    {
        public ISysScheduledTaskService scheduledTaskService = null;
        public JobServiceListener(ISysScheduledTaskService _scheduledTaskService)
        {
            scheduledTaskService = _scheduledTaskService;
        }

        public string Name => GetType().Name;

        /// <summary>
        /// 执行失败
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Console.Error.WriteLineAsync("JobExecutionVetoed");
        }
        /// <summary>
        /// 执行之前
        /// </summary>
        /// <param name="context"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default)
        {
            await Console.Error.WriteLineAsync("JobToBeExecuted");
        }
        /// <summary>
        /// 执行之后
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException? jobException, CancellationToken cancellationToken = default)
        {
            string JobKeyName = context.JobDetail.Key.Name;

            double JobRunTotalMilliseconds = context.JobRunTime.TotalMilliseconds;
            SysScheduledTask sysScheduledTask = scheduledTaskService.GetScheduledTaskByJobKeyName(JobKeyName);
            if (sysScheduledTask != null)
            {
                sysScheduledTask.LastExecutionTime = DateTime.Now;
                sysScheduledTask.NextExecutionTime = context.NextFireTimeUtc.Value.LocalDateTime;
                sysScheduledTask.ExecutionTimeConsuming = Math.Round(JobRunTotalMilliseconds / 1000, 5);
                scheduledTaskService.Update(sysScheduledTask);
            }
            await Console.Error.WriteLineAsync("JobWasExecuted");
        }
    }
}
